package com.estore.service;

import com.estore.model.Product;

import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ProductService implements Serializable {
    private static final long serialVersionUID = 1L;

    // 使用更具体的Map类型
    private Map<String, Product> productData = new HashMap<>();
    private final String dataFilePath;

    // 提供构造函数的灵活性
    public ProductService() {
        this("products.dat");
    }

    public ProductService(String dataFilePath) {
        this.dataFilePath = Objects.requireNonNull(dataFilePath, "Data file path cannot be null");
        loadData();

        if (productData.isEmpty()) {
            initializeDefaultProducts();
        }
    }

    private void initializeDefaultProducts() {
        Set<String> programmingTags = Set.of("编程", "计算机", "畅销");
        Set<String> healthTags = Set.of("健康", "养生");
        Set<String> luxuryTags = Set.of("奢侈品", "收藏", "限量");

        addProduct(new Product("p001", "Java从入门到精通", 99.0, 100, programmingTags));
        addProduct(new Product("p002", "高性能MySQL", 128.5, 50, programmingTags));
        addProduct(new Product("p003", "颈椎康复指南", 45.0, 200, healthTags));
        addProduct(new Product("p004", "生发秘籍", 88.0, 0, healthTags)); // 库存为0的商品
        addProduct(new Product("p005", "倚天屠龙刀", 888888.0, 1, luxuryTags));

        saveData();
    }

    // 产品管理方法
    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public List<Product> getAvailableProducts() {
        return productData.values().stream()
                .filter(product -> product.getStock() > 0)
                .toList();
    }

    public List<Product> searchProductsByName(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getAllProducts();
        }

        String lowerKeyword = keyword.toLowerCase();
        return productData.values().stream()
                .filter(product -> product.getName().toLowerCase().contains(lowerKeyword))
                .toList();
    }

    public List<Product> searchProductsByTag(String tag) {
        if (tag == null || tag.trim().isEmpty()) {
            return getAllProducts();
        }

        String lowerTag = tag.toLowerCase();
        return productData.values().stream()
                .filter(product -> product.getTags().stream()
                        .anyMatch(productTag -> productTag.toLowerCase().contains(lowerTag)))
                .toList();
    }

    public Product findProductById(String id) {
        return productData.get(id);
    }

    public boolean addProduct(Product product) {
        if (product == null || productData.containsKey(product.getId())) {
            return false;
        }
        productData.put(product.getId(), product);
        saveData(); // 自动保存
        return true;
    }

    public boolean updateProduct(Product product) {
        if (product == null || !productData.containsKey(product.getId())) {
            return false;
        }
        productData.put(product.getId(), product);
        saveData(); // 自动保存
        return true;
    }

    public boolean deleteProduct(String id) {
        if (id == null || !productData.containsKey(id)) {
            return false;
        }
        productData.remove(id);
        saveData(); // 自动保存
        return true;
    }

    public boolean updateStock(String productId, int newStock) {
        Product product = findProductById(productId);
        if (product == null || newStock < 0) {
            return false;
        }

        product.setStock(newStock);
        saveData(); // 自动保存
        return true;
    }

    public boolean decreaseStock(String productId, int quantity) {
        Product product = findProductById(productId);
        if (product == null || quantity <= 0 || product.getStock() < quantity) {
            return false;
        }

        product.setStock(product.getStock() - quantity);
        saveData(); // 自动保存
        return true;
    }

    public boolean increaseStock(String productId, int quantity) {
        Product product = findProductById(productId);
        if (product == null || quantity <= 0) {
            return false;
        }

        product.setStock(product.getStock() + quantity);
        saveData(); // 自动保存
        return true;
    }

    // 数据持久化方法
    public void saveData() {
        try {
            Path path = Paths.get(dataFilePath);
            Path parentDir = path.getParent();
            if (parentDir != null) {
                Files.createDirectories(parentDir);
            }

            try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
                out.writeObject(productData);
                System.out.println("产品数据保存成功！文件路径: " + dataFilePath);
            }
        } catch (IOException e) {
            System.err.println("数据保存失败: " + e.getMessage());
            // 可以考虑抛出自定义异常
            throw new RuntimeException("无法保存产品数据", e);
        }
    }

    public void loadData() {
        Path path = Paths.get(dataFilePath);
        if (!Files.exists(path)) {
            System.out.println("数据文件不存在，将创建新文件: " + dataFilePath);
            return;
        }

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(dataFilePath))) {
            @SuppressWarnings("unchecked")
            Map<String, Product> loadedData = (Map<String, Product>) in.readObject();
            productData.clear();
            productData.putAll(loadedData);
            System.out.println("产品数据加载成功！加载了 " + productData.size() + " 个产品");
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("数据加载失败: " + e.getMessage());
            productData.clear();
            // 可以考虑抛出自定义异常或记录更详细的日志
        }
    }

    // 工具方法
    public int getProductCount() {
        return productData.size();
    }

    public boolean productExists(String id) {
        return productData.containsKey(id);
    }

    public List<String> getAllTags() {
        return productData.values().stream()
                .flatMap(product -> product.getTags().stream())
                .distinct()
                .sorted()
                .toList();
    }

    // 备份和恢复方法
    public boolean backupData(String backupFilePath) {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(backupFilePath))) {
            out.writeObject(productData);
            System.out.println("数据备份成功: " + backupFilePath);
            return true;
        } catch (IOException e) {
            System.err.println("数据备份失败: " + e.getMessage());
            return false;
        }
    }

    public boolean restoreFromBackup(String backupFilePath) {
        File backupFile = new File(backupFilePath);
        if (!backupFile.exists()) {
            System.err.println("备份文件不存在: " + backupFilePath);
            return false;
        }

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(backupFile))) {
            @SuppressWarnings("unchecked")
            Map<String, Product> backupData = (Map<String, Product>) in.readObject();
            productData.clear();
            productData.putAll(backupData);
            saveData(); // 保存到当前数据文件
            System.out.println("数据恢复成功！");
            return true;
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("数据恢复失败: " + e.getMessage());
            return false;
        }
    }
}